package com.richfit.barcodesystem_cczt.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.material.tabs.TabLayout;
import com.google.gson.reflect.TypeToken;
import com.richfit.barcodesystem_cczt.activitis.adapters.Detail_Adapter;
import com.richfit.barcodesystem_cczt.activitis.model.base.Result;
import com.richfit.barcodesystem_cczt.activitis.model.users.UserInfo;
import com.richfit.barcodesystem_cczt.databinding.FragmentInformationServiceLqcxBinding;
import com.richfit.barcodesystem_cczt.databinding.FragmentInformationServiceWzcxBinding;
import com.richfit.barcodesystem_cczt.databinding.FragmentInformationServiceXhcxBinding;
import com.richfit.barcodesystem_cczt.fragments.adapters.Information_Adapter;
import com.richfit.barcodesystem_cczt.fragments.base.BaseFragment;
import com.richfit.barcodesystem_cczt.fragments.model.InventoriesEntity;
import com.richfit.barcodesystem_cczt.fragments.model.ZBoxEntity;
import com.richfit.barcodesystem_cczt.network.OkHttpUtils;
import com.richfit.barcodesystem_cczt.utils.Urls;
import com.richfit.barcodesystem_cczt.utils.constant.CCZT_BizConfig;
import com.richfit.barcodesystem_cczt.utils.dialog.DialogHelper;
import com.richfit.barcodesystem_cczt.utils.sharedPreferences.DatabaseHelper;
import com.richfit.barcodesystem_cczt.utils.toast.ToastUtil;
import com.richfit.barcodesystem_cczt.widget.RichAutoEditText;

import java.math.BigDecimal;
import java.util.List;

public class InformationService extends BaseFragment {
    private FragmentInformationServiceXhcxBinding binding_xh;
    private FragmentInformationServiceWzcxBinding binding_wz;
    private FragmentInformationServiceLqcxBinding binding_lq;

    private String bizType;

    public InformationService(String bizType) {
        this.bizType = bizType;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return init(inflater, container);
    }

    /**
     * 初始化要显示的功能页面
     */
    private View init(LayoutInflater inflater, ViewGroup container) {
        View view = null;
        switch (bizType) {
            case CCZT_BizConfig.XHCX:
                //箱号查询
                binding_xh = FragmentInformationServiceXhcxBinding.inflate(inflater, container, false);
                view = binding_xh.getRoot();
                init_xh();
                break;
            case CCZT_BizConfig.WZCX:
                //物资条码查询
                binding_wz = FragmentInformationServiceWzcxBinding.inflate(inflater, container, false);
                view = binding_wz.getRoot();
                init_wz();
                break;
            case CCZT_BizConfig.LQCX:
                //料签信息查询
                binding_lq = FragmentInformationServiceLqcxBinding.inflate(inflater, container, false);
                view = binding_lq.getRoot();
                init_lq();
                break;
        }
        return view;
    }

    //========================箱号查询开始================================
    void init_xh() {
        binding_xh.tabLayoutTitle.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int selectTab = tab.getPosition();
                if (selectTab == -1 || selectTab == 0) {
                    binding_xh.icdHead.getRoot().setVisibility(View.VISIBLE);
                    binding_xh.icdDetail.getRoot().setVisibility(View.GONE);
                } else if (selectTab == 1) {
                    binding_xh.icdHead.getRoot().setVisibility(View.GONE);
                    binding_xh.icdDetail.getRoot().setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
        //箱号输入后并点击
        binding_xh.icdHead.etBoxNum.setOnRichAutoEditTouchListener((view, text) -> {
            getRefData(text);
        });

    }

    /**
     * 查询箱单信息
     *
     * @param zboxBarcode
     */
    private void getRefData(String zboxBarcode) {
        DialogHelper dialogHelper = new DialogHelper(this.getActivity());
        dialogHelper.showLoadingDialog("正在查询装箱单信息");
        OkHttpUtils okHttpUtils = OkHttpUtils.getInstance();
        okHttpUtils.doGet(Urls.URL_ZBOX_LINE + "?zboxBarcode=" + zboxBarcode, bo.cookie, new OkHttpUtils.NetCallBack() {

            @Override
            public void onSuccess(Result result) {
                dialogHelper.dismissDialog();
                String data = gson.toJson(result.getData());
                ZBoxEntity.Line line = gson.fromJson(data, ZBoxEntity.Line.class);
                setItemContent(line);
            }

            @Override
            public void onFailure(Exception e) {
                dialogHelper.dismissDialog();
            }
        });
    }

    /**
     * 填充数据
     *
     * @param line
     */
    private void setItemContent(ZBoxEntity.Line line) {
        //箱子ID
        binding_xh.icdHead.etBoxNum.setTag(line.getId());
        //箱号清空
        binding_xh.icdHead.etBoxNum.setText("");
        //箱号显示
        binding_xh.icdHead.TxtBoxNum.setText(line.getZboxBarcode());
        //装箱单号
        binding_xh.icdHead.etFboxNum.setText(line.getZboxBarcode().substring(0, line.getZboxBarcode().length() - 4));

        //包装方式
        binding_xh.icdHead.etPackageManner.setText(line.getPackingSpec());
        //长
        binding_xh.icdHead.etLength.setText(line.getsLength());
        //宽
        binding_xh.icdHead.etWidth.setText(line.getsWidth());
        //高
        binding_xh.icdHead.etHeight.setText(line.getsHeight());
        //体积
        binding_xh.icdHead.etVolume.setText(line.getsVolume());
        //净重
        binding_xh.icdHead.etNetWeight.setText(line.getsNetWeight());
        //毛重
        binding_xh.icdHead.etGrossWeight.setText(line.getsGrossWeight());
//        //上架仓位
//        binding_xh.icdHead.etLocation.setText(line.getLocation());
        //查询明显
        getBoxDetail(line.getId());
    }

    private void getBoxDetail(String boxId) {
        DialogHelper dialogHelper = new DialogHelper(this.getActivity());
        dialogHelper.showLoadingDialog("正在获取装箱单详情信息");
        OkHttpUtils okHttpUtils = OkHttpUtils.getInstance();
        okHttpUtils.doGet(Urls.URL_ZBOX_DETAIL + "?zboxLineId=" + boxId, bo.cookie, new OkHttpUtils.NetCallBack() {
            @Override
            public void onSuccess(Result result) {
                dialogHelper.dismissDialog();
                String data = gson.toJson(result.getData());
                List<ZBoxEntity.Detail> details = gson.fromJson(data, new TypeToken<List<ZBoxEntity.Detail>>() {
                }.getType());
                Detail_Adapter detail_adapter = new Detail_Adapter(getActivity(), details);
                binding_xh.icdDetail.LVDetail.setAdapter(detail_adapter);
            }

            @Override
            public void onFailure(Exception e) {
                dialogHelper.dismissDialog();
            }
        });
    }

    //========================箱号查询结束================================
    //========================物资条码查询开始================================
    void init_wz() {
        binding_wz.tabLayoutTitle.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int selectTab = tab.getPosition();
                if (selectTab == -1 || selectTab == 0) {
                    binding_wz.icdHead.getRoot().setVisibility(View.VISIBLE);
                    binding_wz.icdDetail.getRoot().setVisibility(View.GONE);
                } else if (selectTab == 1) {
                    binding_wz.icdHead.getRoot().setVisibility(View.GONE);
                    binding_wz.icdDetail.getRoot().setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
        binding_wz.icdHead.etMaterialId.setOnClickListener(v -> binding_wz.icdHead.etMaterialId.setText(""));
        //箱号输入后并点击
        binding_wz.icdHead.etMaterialId.setOnRichAutoEditTouchListener((view, text) -> {
            String requestParam = "materialIds=" + text;
            getRefZLData(requestParam, 0);
        });
    }


    private void setHeadContent(InventoriesEntity.RowsBean rowsBean, BigDecimal sum) {
        binding_wz.icdHead.TxtMaterialDesc.setText(rowsBean.getMaterialDesc());
        binding_wz.icdHead.TxtUnit.setText(rowsBean.getUnit());
        binding_wz.icdHead.TxtAvailableQuantitySum.setText(sum.toString());
    }

    private void setDetailList(List<InventoriesEntity.RowsBean> rows) {
        Information_Adapter adapter = new Information_Adapter(this.getActivity(), rows);
        binding_wz.icdDetail.LVDetail.setAdapter(adapter);
    }

    //========================物资条码查询结束================================
    //========================料签信息查询开始================================
    void init_lq() {
        binding_lq.tabLayoutTitle.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int selectTab = tab.getPosition();
                if (selectTab == -1 || selectTab == 0) {
                    binding_lq.icdHead.getRoot().setVisibility(View.VISIBLE);
                    binding_lq.icdDetail.getRoot().setVisibility(View.GONE);
                } else if (selectTab == 1) {
                    binding_lq.icdHead.getRoot().setVisibility(View.GONE);
                    binding_lq.icdDetail.getRoot().setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
        binding_lq.icdHead.etMaterialId.setOnClickListener(v -> binding_lq.icdHead.etMaterialId.setText(""));
        //箱号输入后并点击
        binding_lq.icdHead.etMaterialId.setOnRichAutoEditTouchListener((view, text) -> {

            String requestParam = "materialIds=" + text;
            getRefZLData(requestParam, 1);
        });
    }


    private void setLqHeadContent(InventoriesEntity.RowsBean rowsBean, BigDecimal sum) {
        binding_lq.icdHead.TxtMaterialDesc.setText(rowsBean.getMaterialDesc());
        binding_lq.icdHead.TxtUnit.setText(rowsBean.getUnit());
        binding_lq.icdHead.TxtAvailableQuantitySum.setText(sum.toString());
    }

    private void setLqDetailList(List<InventoriesEntity.RowsBean> rows) {
        Information_Adapter adapter = new Information_Adapter(this.getActivity(), rows);
        binding_lq.icdDetail.LVDetail.setAdapter(adapter);
    }
    //========================料签信息查询结束================================
    //箱号条码--编码规则
//    if (list != null && list.length == 2) {
//        if (!TextUtils.isEmpty(list[0]) && !TextUtils.isEmpty(list[1])) {
//            String zboxNum = list[0].concat(list[1]);
//            etZboxNum.setText(zboxNum);
//            RequestParam requestParam = new RequestParam();
//            requestParam.boxBarcode = zboxNum;
//            mPresenter.getBoxInfo(requestParam);
//        }
//    }
    //物资条码--编码规则
//     if (list != null && list.length >= 13) {
//        materialNum.setText(list[2]);
//        zboxNum.setText(list[13]);
//        boxNum.setText(list[14]);
//        batchFlag.setText(list[12]);
//        RequestParam param = new RequestParam();
//        param.queryType = "01";
//        param.materialNum = list[2];
//        mPresenter.getMaterialInfo(param);
//    }

    //料签编码--编码规则
    //F20EF4A3F1159E461CCA32CC5896C903|453136F6B8E2922D5F71F0FA1FED012B|02-01-01|47032451|10000000004|5A4A36|
    //工厂Id|库存地点Id|仓位|物料组|物资编码|组织单位的十六进制|
    @Override
    public void handleBarCodeScanResult(String type, String[] list) {
        if (list != null) {
            //获取当前焦点所在的控件
            View vFocus = this.getActivity().getWindow().getDecorView().findFocus();

            if (vFocus instanceof RichAutoEditText) {
                RichAutoEditText richAutoEditText = (RichAutoEditText) vFocus;
                if (richAutoEditText.getId() == binding_xh.icdHead.etBoxNum.getId()) {
                    //抬头 装箱单
                    String zboxNum = list[0].concat(list[1]);
                    binding_xh.icdHead.etBoxNum.setText(zboxNum);
                    getRefData(zboxNum);
                    binding_xh.icdHead.etBoxNum.setText("");
                } else if (richAutoEditText.getId() == binding_wz.icdHead.etMaterialId.getId()) {
//                    物资条码
                    //materialNum.setText(list[2]);
//        zboxNum.setText(list[13]);
//        boxNum.setText(list[14]);
                    String requestParam = "materialIds=" + list[2] + "&zboxNum=" + list[13] + "&boxNum=" + list[14];
                    binding_wz.icdHead.etMaterialId.setText(list[2]);
                    getRefZLData(requestParam, 0);
                } else if (richAutoEditText.getId() == binding_lq.icdHead.etMaterialId.getId()) {
//料签编码
//    //F20EF4A3F1159E461CCA32CC5896C903|453136F6B8E2922D5F71F0FA1FED012B|02-01-01|47032451|10000000004|5A4A36|
//    //工厂Id|库存地点Id|仓位|物料组|物资编码|组织单位的十六进制|
                    String requestParam = "materialIds=" + list[4] + "&location=" + list[2];
                    binding_wz.icdHead.etMaterialId.setText(list[4]);
                    getRefZLData(requestParam, 1);
                }

            }
            ToastUtil.showTextShort(list[0]);
        }
    }

    /**
     * 查询装箱单信息
     *
     * @param requestParam
     */
    private void getRefZLData(String requestParam, int type) {
        UserInfo userInfo = gson.fromJson(DatabaseHelper.getSp(bo.userinfo, ""), UserInfo.class);

        //Todo 测试使用
        userInfo.getOrg().setOrgCode("C100034");
        //Todo 测试使用
        DialogHelper dialogHelper = new DialogHelper(this.getActivity());
        dialogHelper.showLoadingDialog("正在查询装箱单信息");
        OkHttpUtils okHttpUtils = OkHttpUtils.getInstance();
        //"?orgId=C100034&materialIds=10000000004&specialFlags=WH-0000006000000001&invTypes=WH-0000007000000001",
        okHttpUtils.doGet(Urls.URL_INVENTORIES +
                        "?orgId=" + userInfo.getOrg().getOrgCode() + "&specialFlags=WH-0000006000000001&invTypes=WH-0000007000000001" +
                        "&" + requestParam,
                bo.cookie, new OkHttpUtils.NetCallBack() {

                    @Override
                    public void onSuccess(Result result) {
                        dialogHelper.dismissDialog();
                        String data = gson.toJson(result.getData());
                        InventoriesEntity inventoriesEntity = gson.fromJson(data, InventoriesEntity.class);
                        if (inventoriesEntity.getRows().size() <= 0) {
                            return;
                        }
                        //计算总库存数量
                        BigDecimal sum = BigDecimal.ZERO;
                        for (InventoriesEntity.RowsBean rowsBean : inventoriesEntity.getRows()) {
                            sum = sum.add(rowsBean.getAvailableQuantity());
                        }
                        if (type == 0) {
                            //设置抬头页面的信息
                            setHeadContent(inventoriesEntity.getRows().get(0), sum);
                            //设置详情列表信息
                            setDetailList(inventoriesEntity.getRows());
                        } else if (type == 1) {
                            //设置抬头页面的信息
                            setLqHeadContent(inventoriesEntity.getRows().get(0), sum);
                            //设置详情列表信息
                            setLqDetailList(inventoriesEntity.getRows());
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        dialogHelper.dismissDialog();
                    }
                });
    }
}